package com.example.petstore_2.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.petstore_2.common.CommonResponse;
import com.example.petstore_2.domain.User;
import com.example.petstore_2.domain.UserInfo;
import com.example.petstore_2.service.CodeService;
import com.example.petstore_2.service.UserInfoService;
import com.example.petstore_2.service.UserService;
import com.example.petstore_2.util.GiteeLogin;
import com.example.petstore_2.util.JWTUtil;
import com.example.petstore_2.util.VerifyCode;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.flogger.Flogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UserController {

    @Autowired
    private DefaultKaptcha captchaProducer;
    @Autowired
    private UserService userService;
    @Autowired
    private CodeService codeService;
    @Autowired
    private UserInfoService userInfoService;

    /**
     * 用户名密码登录
     * @param requestBody
     * @return
     */
    @PostMapping("/token/username")
    public CommonResponse loginByName(@RequestBody JSONObject requestBody){

        String username = requestBody.getString("username");
        String password = requestBody.getString("password");
        String code = requestBody.getString("code");

//        String verifyCode = VerifyCode.getCode();
//        if(!verifyCode.equals(code)){
//            return CommonResponse.creatForError("验证码错误");
//        }

        CommonResponse commonResponse = userService.findUserByUsernameAndPassword(username, password);

        if(commonResponse.isSuccess()){
            Map<String, String> payload = new HashMap<>();
            User user = (User) commonResponse.getData();
            payload.put("id", "" + user.getId());
            payload.put("username",user.getUsername());
            // 生成jwt令牌
            String token = JWTUtil.getToken(payload);
            Map<String, Object> res = new HashMap<>();
            res.put("token", token);
            res.put("username", username);
            return CommonResponse.creatForSuccess(res);
        }
        return CommonResponse.creatForError(commonResponse.getMessage());
    }

    /**
     * gitee登录
     * @param code
     * @return
     */
    @GetMapping("/token/gitee/{code}")
    public CommonResponse loginByGitee(@PathVariable("code") String code){
//        从code中获取gitee用户信息
        String userInfo = GiteeLogin.getUserInfo(code, "login");
        String giteeid = JSONObject.parseObject(userInfo).get("id").toString();
        CommonResponse commonResponse = userService.findUserByGiteeId(giteeid);
        if(commonResponse.isSuccess()){
            User user = (User) commonResponse.getData();
            Map<String, String> payload = new HashMap<>();
            payload.put("id", "" + user.getId());
            payload.put("username",user.getUsername());
            // 生成jwt令牌
            String token = JWTUtil.getToken(payload);
            Map<String, Object> res = new HashMap<>();
            res.put("token", token);
            res.put("username", user.getUsername());
            return CommonResponse.creatForSuccess(res);
        }else{
            return commonResponse;
        }
    }


    /**
     * 手机号登录
     * @param requestBody
     * @return
     */
    @PutMapping("/token/phone")
    public CommonResponse loginByPhone(@RequestBody JSONObject requestBody){
        String phoneNumber = requestBody.getString("phoneNumber");
        String phoneCode = requestBody.getString("phoneCode");

        CommonResponse commonResponse = userService.loginByPhone(phoneNumber, phoneCode);
        if(commonResponse.isSuccess()){
            Map<String, String> payload = new HashMap<>();
            User user = (User) commonResponse.getData();
            payload.put("id", "" + user.getId());
            payload.put("username",user.getUsername());
            // 生成jwt令牌
            String token = JWTUtil.getToken(payload);
            Map<String, Object> res = new HashMap<>();
            res.put("token", token);
            res.put("username", user.getUsername());
            return CommonResponse.creatForSuccess(res);
        }
        return CommonResponse.creatForError(commonResponse.getMessage());
    }

    /**
     * 用户登录时发送手机验证码
     * @param phoneNumber
     * @return
     */
    @PutMapping("/loginPhoneCode/{phoneNumber}")
    public CommonResponse sendPhoneCodeForUserLogin(@PathVariable("phoneNumber") String phoneNumber){
        return codeService.sendPhoneCodeForUser(phoneNumber, "login");
    }

    /**
     * 用户注册时发送手机验证码
     * @param phoneNumber
     * @return
     */
    @PutMapping("/registerCode/{phoneNumber}")
    public CommonResponse sendPhoneCodeForUserRegister(@PathVariable("phoneNumber") String phoneNumber){
        CommonResponse commonResponse = userService.findUserByPhoneNumber(phoneNumber);
        if(commonResponse.isSuccess()){
            return CommonResponse.creatForError("该手机号已被注册");
        }
        return codeService.sendPhoneCodeForUser(phoneNumber, "register");
    }

    /**
     * 重置密码时发送验证码
     * @param phoneNumber
     * @return
     */
    @PutMapping("/resetPhoneCode/{phoneNumber}")
    public CommonResponse sendPhoneCodeForUserResetPassword(@PathVariable("phoneNumber") String phoneNumber){
        return codeService.sendPhoneCodeForUser(phoneNumber, "reset");
    }

    /**
     * 重置密码
     * @param requestBody
     * @return
     */
    @PostMapping("/resetPassword")
    public CommonResponse resetPassword(@RequestBody JSONObject requestBody){
        String phoneNumber = requestBody.getString("phoneNumber");
        String password = requestBody.getString("password");
        String phoneCode = requestBody.getString("phoneCode");

        return userService.resetPassword(phoneNumber, password, phoneCode);
    }

    /**
     * 用户gitee注册
     * @param requestBody
     * @return
     */
    @PutMapping("/users/gitee")
    public CommonResponse bindPhoneNumber(@RequestBody JSONObject requestBody){
        String username = requestBody.getString("username");
        String phoneNumber = requestBody.getString("phoneNumber");
        String phoneCode = requestBody.getString("phoneCode");
        String code = requestBody.getString("code");

//        System.out.println("code " + code);
        CommonResponse commonResponse = userService.findUserByUsername(username);
        if(commonResponse.isSuccess()){
//            手机号绑定页面
            return CommonResponse.creatForError("用户名已被使用");
        }
        commonResponse = userService.findUserByPhoneNumber(phoneNumber);
        if(commonResponse.isSuccess()){
//            手机号已被绑定
            return CommonResponse.creatForError("手机号已被绑定");
        }

//        String giteeUserInfo = GiteeLogin.getUserInfo(code, "register");
        String giteeUserInfo = GiteeLogin.getUserInfo(code, "register");
        String giteeid = JSONObject.parseObject(giteeUserInfo).get("id").toString();
        commonResponse = userService.findUserByGiteeId(giteeid);
        if(commonResponse.isSuccess()){
            return CommonResponse.creatForError("该gitee已注册");
        }
//        判断验证码是否合法
        commonResponse = codeService.checkPhoneCodeForUserRegister(phoneNumber, phoneCode);
        if(commonResponse.isSuccess()){
//            验证码合法
//            创建用户
            CommonResponse commonResponse1 = userService.saveUserByPhoneNumberAndGitee(username, phoneNumber, giteeid);
            if(commonResponse1.isSuccess()) {



                return CommonResponse.creatForSuccessMessage("注册成功");
            }
//            绑定失败
            return CommonResponse.creatForError("绑定失败");
        }else{
            return CommonResponse.creatForError(commonResponse.getMessage());
        }
    }

    /**
     * 用手机号注册
     * @param requestBody
     * @return
     */
    @PutMapping("/users/phone")
    public CommonResponse registerByPhone(@RequestBody JSONObject requestBody){
        String username = requestBody.getString("username");
        String password = requestBody.getString("password");
        String phoneNumber = requestBody.getString("phoneNumber");
        String phoneCode = requestBody.getString("phoneCode");

//        判断用户名是否被用
        CommonResponse commonResponse = userService.findUserByUsername(username);
        if(commonResponse.isSuccess()){
//            model.addAttribute("errorMsg", "用户名已被使用");
//            到注册页面
            return CommonResponse.creatForError("用户名已被使用");
        }
//        判断手机号是否被用
        commonResponse = userService.findUserByPhoneNumber(phoneNumber);
        if(commonResponse.isSuccess()){
//            model.addAttribute("errorMsg", "手机号已被使用");
//            到注册页面
//            return "user/registerBuyer";
            return CommonResponse.creatForError("手机号已被使用");
        }
//        判断手机验证码是否正确
        commonResponse = codeService.checkPhoneCodeForUserRegister(phoneNumber, phoneCode);
        if(commonResponse.isSuccess()){
            commonResponse = userService.saveUserByPhone(username, password, phoneNumber);
            if(commonResponse.isSuccess()){
                System.out.println("初测成功");
//                注册成功
                return CommonResponse.creatForSuccessMessage("注册成功");
            }else{
//                注册失败
                System.out.println(" 注册失败");
                return CommonResponse.creatForError("注册失败");
            }
        }else{
            System.out.println("  到注册页面");
//            到注册页面
//            model.addAttribute("errorMsg", commonResponse.getMessage());
            return CommonResponse.creatForError(commonResponse.getMessage());
        }
    }

    /**
     * 判断手机号是否已经被注册
     * @param phoneNumber
     * @return
     */
    @GetMapping("/users/phone/{phoneNumber}")
    public CommonResponse findUserByPhoneNumber(@PathVariable("phoneNumber") String phoneNumber){
        CommonResponse commonResponse = userService.findUserByPhoneNumber(phoneNumber);
        if(commonResponse.isSuccess()){
            return CommonResponse.creatForSuccessMessage("手机号已注册");
        }else{
            return CommonResponse.creatForError("手机号未注册");
        }
    }

    /**
     * 判断用户名是否已经被注册
     * @param username
     * @return
     */
    @GetMapping("/users/username/{username}")
    public CommonResponse findUserByUsername(@PathVariable("username") String username){
        CommonResponse commonResponse = userService.findUserByUsername(username);
        if(commonResponse.isSuccess()){
            return CommonResponse.creatForSuccessMessage("用户名已存在");
        }else{
            return CommonResponse.creatForError("用户名不存在");
        }
    }

    /**
     * 判断gitee是否被注册
     * @param code
     * @return
     */
    @GetMapping("/user/gitee/{code}")
    public CommonResponse findUserByGitee(@PathVariable("code") String code){
        String giteeUserInfo = GiteeLogin.getUserInfo(code, "register");
        String giteeid = JSONObject.parseObject(giteeUserInfo).get("id").toString();
        CommonResponse commonResponse = userService.findUserByGiteeId(giteeid);
        if(commonResponse.isSuccess()){
            return CommonResponse.creatForSuccessMessage("账号已被注册");
        }else{
            return CommonResponse.creatForError("账号未被注册");
        }
    }


    /**
     * 获取用户个人信息
     * @param token
     * @return
     */
    @GetMapping("/userInfos")
    public CommonResponse getInfos(@RequestHeader("Authorization") String token){
        String username = JWTUtil.getTokenInfo(token, "username");
        return userInfoService.getUserInfoByUsername(username);
    }

    /**
     * 修改个人信息
     * @param userInfo
     * @param token
     * @return
     */
    @PostMapping("/userInfos")/* need test*/
    public CommonResponse postChangeInfo(@RequestBody UserInfo userInfo, @RequestHeader("Authorization") String token){
        System.out.println(userInfo);
        String username = JWTUtil.getTokenInfo(token, "username");
//        todo:update有问题,需要测试
        CommonResponse commonResponse = userInfoService.updateUserInfo(username, userInfo);
        if(commonResponse.isSuccess()){
//            model.addAttribute("msg", "修改成功");
//            model.addAttribute("userInfo", commonResponse.getData());
            return CommonResponse.creatForSuccessMessage("修改成功");
        }else{
//            model.addAttribute("errorMsg", "修改失败");
            return CommonResponse.creatForError("修改失败");
        }
    }

    @GetMapping("/common/kaptcha")/*需要保留*/
    public void defaultKaptcha(HttpServletResponse httpServletResponse) throws Exception {
        byte[] captchaOutputStream = null;
        ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream();
        try {
            String verifyCode = captchaProducer.createText();
            VerifyCode.setCode(verifyCode);
            System.out.println(verifyCode);
            BufferedImage challenge = captchaProducer.createImage(verifyCode);
            ImageIO.write(challenge, "jpg", imgOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        captchaOutputStream = imgOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaOutputStream);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    @GetMapping("/gitee/login")
    public CommonResponse getGiteeLogin(){
        return CommonResponse.creatForSuccess(GiteeLogin.getLoginForm());
    }

    @GetMapping("/gitee/register")
    public CommonResponse getGiteeRegister(){
        return CommonResponse.creatForSuccess(GiteeLogin.getReigsterForm());
    }
}
